package com.ficus.road.maintain.third.zh.xlj;

import com.alibaba.fastjson.JSONArray;
import com.ficus.road.maintain.core.model.zh.xlj.XljWarning;
import com.ficus.road.maintain.core.model.zh.xlj.XljWarningZH;
import com.ficus.road.maintain.core.utils.JsonUtils;
import com.ficus.road.maintain.dao.xlj.XljWarningDao;
import com.ficus.road.maintain.third.zh.BaseZH;
import com.ficus.road.maintain.util.MyDateUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xiawen yang
 * @date 2022/6/27 下午7:34
 */
@Component
public class ZHXljWarningList extends BaseZH {

    @Value("${present.flag}")
    private Boolean present;
    @Autowired
    private XljWarningDao xljWarningDao;

    @PostConstruct
    void init() {
        arg0 = "xljWarningList";
        errMsg = "调用中海接口获取下立交预警数据异常!";
        successMsg = "调用中海接口获取下立交预警数据成功!";
    }

    //    @Scheduled(cron = "0/5 * * * * ?", zone = "GMT+8:00")
    @Scheduled(cron = "${xlj.sync_cron}", zone = "GMT+8:00")
    public void refreshXljWarningList() {
        String todayStr = MyDateUtil.dateFormatStr(new Date(), "yyyy-MM-dd");
//        todayStr = "2023-01-01";
        arg1 = "{\"START_TIME\":\"" + todayStr + "\"}";
        String xljWarningStr = getZHData();
        Date date = new Date();
        List<XljWarningZH> xljWarningZHList = JSONArray.parseArray(xljWarningStr, XljWarningZH.class);
        if (CollectionUtils.isEmpty(xljWarningZHList)) return;
        List<XljWarning> xljWarningList = xljWarningZHList.stream().map(item -> item.convert2XljWarning(item, date)).collect(Collectors.toList());
        xljWarningList.forEach(item -> {
            XljWarning fetch = xljWarningDao.fetch(item.getId());
            if (ObjectUtils.isNotEmpty(fetch)) {
                XljWarning merge = JsonUtils.merge(fetch, item, XljWarning.class);
                xljWarningDao.saveOrUpdate(merge);
            } else {
                xljWarningDao.saveOrUpdate(item);
            }
        });
    }

    @Override
    public boolean printLogInfo() {
        return false;
    }
}
